<script setup lang='ts'>
import { useGetModelList } from '@fl/api/man-api/pricing-tool'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const props = withDefaults(defineProps<{
    currentCategoryId?: string
    currentItemId?: string
    modelIdList?: any
    projectId?: string

}>(), {
    currentCategoryId: '',
    currentItemId: '',
    modelIdList: () => {},
    projectId: '',

})
const emits = defineEmits(['save'])
const title = ref<string>('添加型号')

const { currentCategoryId, currentItemId, modelIdList, projectId } = toRefs(props)
const visible = defineModel<boolean>('visible', { required: true })

const params = computed(() => ({
    categoryId: currentCategoryId.value,
    itemId: currentItemId.value,
    projectId: projectId.value,
}))

const { data: tableData, isLoading, refetch } = useGetModelList(params)
const result = ref<any>([])
watchEffect(() => {
    if (currentCategoryId.value && currentItemId.value) {
        refetch()
    }
})

watchEffect(() => {
    if (tableData.value) {
        result.value = cloneDeep(tableData.value)
        result.value.forEach((item: any) => {
            if (modelIdList.value.includes(item.modelId)) {
                item.checkFlag = true
                item.isNew = false
            }
            else {
                item.isNew = true
                item.checkFlag = false
            }
        })
    }
})
function cancel() {
    visible.value = false
}

function save() {
    const data = {
        itemId: currentItemId.value,
        result: result.value.filter((item: any) => item.checkFlag && item.isNew),
    }
    emits('save', data)
    visible.value = false
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="600"
                close-on-press-escape
                @cancel="cancel"
    >
        <ElSkeleton v-if="isLoading"
                    animated
        />

        <div v-for="(item) in result"
             :key="item.modelId"
        >
            <el-checkbox v-model="item.checkFlag"
                         :label="item.model"
                         :disabled="item.checkFlag && !item.isNew"
            />
        </div>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           @click="save"
                >
                    保存
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
